//
//  MusicViewController.m
//  MusicPlayer
//
//  Created by lanou3g on 16/5/11.
//  Copyright © 2016年 韩宏. All rights reserved.
//

#import "MusicViewController.h"
#import <UIImageView+WebCache.h>
#import "AVPlayerManager.h"
#import "Tools.h"
#import "LyricTableViewCell.h"
#import "MusicInfoHandle.h"
#import "LyricTools.h"

@interface MusicViewController ()<AVPlayerManagerDelegate, UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate>

@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) IBOutlet UIImageView *singerImageView;
@property (strong, nonatomic) IBOutlet UIImageView *BlurImageView;
@property (strong, nonatomic) IBOutlet UISlider *progressSlider;
@property (strong, nonatomic) IBOutlet UILabel *musicNameLabel;
@property (strong, nonatomic) IBOutlet UILabel *singerLabel;
@property (strong, nonatomic) IBOutlet UILabel *albumLabel;
@property (strong, nonatomic) IBOutlet UILabel *beginTimeLabel;
//总时长,单位ms
@property (strong, nonatomic) IBOutlet UILabel *endTimeLabel;
@property (strong, nonatomic) IBOutlet UIButton *likeButton;
@property (strong, nonatomic) IBOutlet UIButton *lastMusicButton;
@property (strong, nonatomic) IBOutlet UIButton *playerButton;
@property (strong, nonatomic) IBOutlet UIButton *nextMusicButton;
@property (strong, nonatomic) IBOutlet UIButton *volumeLowButton;
@property (strong, nonatomic) IBOutlet UIButton *volumeHighButton;
@property (strong, nonatomic) IBOutlet UISlider *volumeSlider;
@property (strong, nonatomic) IBOutlet UIButton *listButton;
@property (strong, nonatomic) IBOutlet UIButton *packUpButton;
//顺序播放
@property (strong, nonatomic) IBOutlet UIButton *loopButton;
//随机播放
@property (strong, nonatomic) IBOutlet UIButton *randomButton;
//单曲循环
@property (strong, nonatomic) IBOutlet UIButton *singleLoopButton;
//记录进度条状态,是否开始拖拽进度条
@property (nonatomic, assign) BOOL isSeek;
//记录正在播放的位置
@property (nonatomic, strong) NSIndexPath *singingIndexPath;

@end

@implementation MusicViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [AVPlayerManager shareHandle].delegate = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    //设置音乐图片的圆角
    _singerImageView.layer.cornerRadius = ([UIScreen mainScreen].bounds.size.width - 170) / 2;
    _singerImageView.layer.masksToBounds = YES;
    
    //设置进度条滑动按钮图片
    [_progressSlider setThumbImage:[UIImage imageNamed:@"plane"] forState:UIControlStateNormal];
    [_volumeSlider setThumbImage:[UIImage imageNamed:@"snail"] forState:UIControlStateNormal];
    
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    [self p_setupDataSource];
}

//歌词显示tableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [LyricTools shareLyricHandle].modelArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LyricTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellID"];
    if (!cell) {
        cell = [[LyricTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cellID"];
    }
    
    cell.backgroundColor = [UIColor clearColor];
    
    LyricTools *lyT = [LyricTools shareLyricHandle].modelArray[indexPath.row];
    [cell setvaluesWithLyricTools:lyT];
    
    if (_singingIndexPath == indexPath) {
        cell.lyricLabel.textColor = [UIColor magentaColor];
        cell.lyricLabel.font = [UIFont systemFontOfSize:18.0];
    } else {
        cell.lyricLabel.textColor = [UIColor cyanColor];
        cell.lyricLabel.font = [UIFont systemFontOfSize:14.0];
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (void)p_setupDataSource
{
    [self.singerImageView sd_setImageWithURL:[NSURL URLWithString:_musicInfo.picUrl] placeholderImage:[UIImage imageNamed:@"tiger"]];
    
    [self.BlurImageView sd_setImageWithURL:[NSURL URLWithString:_musicInfo.blurPicUrl] placeholderImage:[UIImage imageNamed:@""]];
    
    self.musicNameLabel.text = _musicInfo.name;
    self.singerLabel.text = _musicInfo.singer;
    self.albumLabel.text = _musicInfo.album;
    
    [[AVPlayerManager shareHandle] playWithMusicUrl:_musicInfo.mp3Url];
    
    //处理歌词
    [[LyricTools shareLyricHandle] lyricWithStr:_musicInfo.lyric];
    [self.tableView reloadData];
    self.singingIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.tableView scrollToRowAtIndexPath:_singingIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    
    //设置progressSlider min max
    _progressSlider.minimumValue = 0;
    _progressSlider.maximumValue = _musicInfo.totalTime;
    _progressSlider.value = 0;
    
    //当前时间、剩余时间label赋值
    _beginTimeLabel.text = @"00:00";
    _endTimeLabel.text = [Tools timeStrFromSeconds:_musicInfo.totalTime];
    
    _volumeSlider.minimumValue = 0.0;
    _volumeSlider.maximumValue = 1.0;
    _volumeSlider.value = [AVPlayerManager shareHandle].volume;
    
    [self changeButtonWithLoopType:[AVPlayerManager shareHandle].loopType];
}

//时间进度条改变
- (IBAction)progressChange:(UISlider *)sender {
    //改变歌曲的播放时间
    [[AVPlayerManager shareHandle] seekToTime:_progressSlider.value];
    _isSeek = NO;
}

//开始触摸时间进度条
- (IBAction)progressTouchDown:(UISlider *)sender {
    _isSeek = YES;
}

//声音进度条
- (IBAction)volumeSliderClicked:(UISlider *)sender {
    [AVPlayerManager shareHandle].volume = _volumeSlider.value;
}

//
- (IBAction)packUpClicked:(UIButton *)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

//喜欢点击时间
- (IBAction)likeClicked:(UIButton *)sender {
    
}

//上一曲
- (IBAction)lastMusicClicked:(UIButton *)sender {
    _musicInfo = [[MusicInfoHandle shareHandle] musicInfoLastWithIndex:&_index];
    //更新播放页面
    [self p_setupDataSource];
}

//点击播放按钮
- (IBAction)playMusicClicked:(UIButton *)sender {
    //判断播放状态,选择不同的按钮
    if ([AVPlayerManager shareHandle].status == AVPlayerPause) {
        [[AVPlayerManager shareHandle] play];
        [_playerButton setImage:[UIImage imageNamed:@"pause"] forState:UIControlStateNormal];
        [_playerButton setImage:[UIImage imageNamed:@"pause_h"] forState:UIControlStateHighlighted];
    } else if ([AVPlayerManager shareHandle].status == AVPlayerPlaying) {
        [[AVPlayerManager shareHandle] pause];
        [_playerButton setImage:[UIImage imageNamed:@"play"] forState:UIControlStateNormal];
    }
}

//下一曲
- (IBAction)nextMusicClicked:(UIButton *)sender {
    _musicInfo = [[MusicInfoHandle shareHandle] musicInfoNextWithIndex:&_index];
    [self p_setupDataSource];
}

//菜单点击事件
- (IBAction)listClicked:(UIButton *)sender {
    
}

//循环播放
- (IBAction)loopClicked:(UIButton *)sender {
    [self changeButtonWithLoopType:OrderTpye];
}

//单曲播放
- (IBAction)singleLoopClicked:(UIButton *)sender {
    [self changeButtonWithLoopType:SingleType];
}

//随机播放
- (IBAction)randomClicek:(UIButton *)sender {
    [self changeButtonWithLoopType:ShuffleType];
}

#pragma mark ---AVPlayerManager Delegate---
- (void)changeTime:(CGFloat)time
{
    if (!_isSeek) {
        //改变进度条
        _progressSlider.value = time;
    }
    //改变播放时间
    _beginTimeLabel.text = [Tools timeStrFromSeconds:time];
    //剩余时间
    _endTimeLabel.text = [NSString stringWithFormat:@"-%@", [Tools timeStrFromSeconds:_musicInfo.totalTime - time]];
    //音乐图片旋转
    [UIView animateWithDuration:0.1 animations:^{
        _singerImageView.transform = CGAffineTransformRotate(_singerImageView.transform, 0.1);
    }];
    
    //当前应该执行的歌词的时间
    NSInteger index = [[LyricTools shareLyricHandle] indexForTime:time];
    if (index > 0) {
        self.singingIndexPath = [NSIndexPath indexPathForRow:index inSection:0];
        [self.tableView scrollToRowAtIndexPath:self.singingIndexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
        [self.tableView reloadData];
    }
}

//一条曲目播放完成
- (void)playFinished
{
    //开始播放下一首
    [self getMusicInfoWithLoopType:[AVPlayerManager shareHandle].loopType];
}

//判断播放类型获取下一首歌
- (void)getMusicInfoWithLoopType:(LoopType)loopType {
    switch (loopType) {
        case SingleType:
            [self p_setupDataSource];
            break;
        case ShuffleType:
            _musicInfo = [[MusicInfoHandle shareHandle] musicInfoRandomWithIndex:&_index];
            [self p_setupDataSource];
            break;
        case OrderTpye:
            _musicInfo = [[MusicInfoHandle shareHandle] musicInfoNextWithIndex:&_index];
            [self p_setupDataSource];
            break;
            
        default:
            break;
    }
}

- (void)changeButtonWithLoopType:(LoopType)loopType
{
    [_singleLoopButton setImage:[UIImage imageNamed:@"singleloop"] forState:UIControlStateNormal];
    [_randomButton setImage:[UIImage imageNamed:@"shuffle"] forState:UIControlStateNormal];
    [_loopButton setImage:[UIImage imageNamed:@"loop"] forState:UIControlStateNormal];
    [AVPlayerManager shareHandle].loopType = loopType;
    switch (loopType) {
        case SingleType:
            [_singleLoopButton setImage:[UIImage imageNamed:@"singleloop-s"] forState:UIControlStateNormal];
            break;
        case ShuffleType:
            [_randomButton setImage:[UIImage imageNamed:@"shuffle-s"] forState:UIControlStateNormal];
            break;
        case OrderTpye:
            [_loopButton setImage:[UIImage imageNamed:@"loop-s"] forState:UIControlStateNormal];
            break;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
